package controller

import (
	"cn.pinming/gencode/core"
	"cn.pinming/gencode/core/api"
	"github.com/kataras/iris/context"
	"github.com/kataras/iris/mvc"
	"github.com/kataras/iris/sessions"
	"strings"
	"time"
)

type BaseController struct {
	Session *sessions.Session
	Data    map[string]interface{} //request 响应结果数据(作用范围，当前请求上下文)
	Ctx     context.Context
}

func (this *BaseController) BeginRequest(ctx context.Context) {
	if this.Session == nil {
		this.Session = core.StartSession(ctx)
	}
	if this.Ctx == nil {
		this.Ctx = ctx
	}
	flag, _ := this.Session.GetBoolean(core.NavCollapseKey)
	if core.GetAppConfig().Debug {
		ctx.ViewData("cssversion", time.Now().Unix())
	} else {
		ctx.ViewData("cssversion", "20170801")
	}
	ctx.ViewData("NavCollapse", flag)
	if this.Data == nil {
		//每一个请求都有唯一的data
		this.Data = make(map[string]interface{})
	}
	url := ctx.Request().RequestURI
	if !strings.HasPrefix(url, "/login") && !this.isLoggedIn() {
		if ctx.IsAjax() {
			ctx.JSON(this.Json(core.UNAUTH, "未登录"))
			return
		}
		ctx.Redirect("/login")
	} else {
		ctx.ViewData("user", core.CurrentUser(this.Session))
	}
}

func (c *BaseController) isLoggedIn() bool {
	user := core.CurrentUser(c.Session)
	return user != nil && user.Uid > 0
}

func (this *BaseController) EndRequest(ctx context.Context) {

}

func (this *BaseController) MakeMap() map[string]interface{} {
	data := make(map[string]interface{})
	return data
}

//构造mvc返回结构
func (this *BaseController) ViewResult(tpl string) mvc.Result {
	if !strings.HasSuffix(tpl, ".html") {
		tpl = tpl + ".html"
	}
	return mvc.View{
		Name: tpl,
		Data: this.Data,
	}
}

func (this *BaseController) Json(code int, msg string) api.Result {
	if len(msg) == 0 {
		if code == core.SUCCESS {
			msg = core.SUCCESS_MSG
		} else {
			msg = core.ERROR_MSG
		}
	}
	result := api.Result{
		Code: code,
		Msg:  msg,
	}
	return result
}

func (this *BaseController) Success() api.Result {
	return this.Json(core.SUCCESS, core.SUCCESS_MSG)
}

func (this *BaseController) Error(msg string) api.Result {
	return this.Json(core.ERROR, msg)
}
